import threading
import time
import socket

class CConnector(threading.Thread):
    def __init__(self, isServer, messageQ, controlQ, port, recv, serverIp="127.0.0.1"):
        self.isServer = isServer
        self.messageQ = messageQ
        self.controlQ = controlQ
    
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.rev = ""
        self.port = port
        self.recv = recv
        self.serverIp  = serverIp

        threading.Thread.__init__(self)
    def run(self):
        if self.isServer == True:
            revcSock = self.startServer()
            self.rev  = revcSock

            #trd = threading.Thread(target=self.rec())
            #trd.start()
            print("connect type")
            print(self.recv)
            if self.recv == True: #sendmsg
                while True:
                    if not self.messageQ.empty():
                        data = self.messageQ.get()
                        if data and isinstance(data,list):
                            sendMsg = ""
                            for d in data:
                                sendMsg = sendMsg+","+str(d)
                            sendMsg = sendMsg.strip(",")
                            print(sendMsg) 
                            self.messageQ.queue.clear()
                            print("server send msg")
                            revcSock.send(bytes(sendMsg,"utf-8"))
                            time.sleep(0.01)
            else:
                while True:
                    t = self.rev.recv(1024)
                    t = bytes.decode(t)
                    print(t)
                    signal = self.controlQ.put(t)
        #client  
        else:
            self.connectServer()

            if self.recv == False:
                while True:
                    if not self.messageQ.empty():
                        data = self.messageQ.get()
                        #data = str(data[0]) + ","+str(data[1])+";"
                        if data and isinstance(data,list):
                            sendMsg = ""
                            for d in data:
                                sendMsg = sendMsg+","+str(d)
                            sendMsg = sendMsg.strip(",")
                            print("client send msg")
                            print(sendMsg) 
                            self.messageQ.queue.clear()
                     
                            self.sock.send(bytes(sendMsg,"utf-8"))
                            time.sleep(0.01)
            else:
                signal = self.controlQ.put(0)
                while True:
                    t = self.sock.recv(1024)
                    t = bytes.decode(t)
                    print("accept:"+t)
                    print(self.port)
                    signal = self.controlQ.put(t)
                

    #start as server
    def startServer(self):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(('8.8.8.8', 80))
            ip = s.getsockname()[0]
        finally:
            s.close()

        port = 123
        self.sock.bind((ip, self.port))
        self.sock.listen(1)
        socknum, addr = self.sock.accept()
        print(addr)

        self.controlQ.put(0)

        return socknum

    #connect to a server
    def connectServer(self):
        while self.sock.connect_ex((self.serverIp, self.port)) != 0:
            self.sock.connect_ex((self.serverIp, self.port))

    #close a server
    def closeServer(self):
        self.sock.close()

    #def rec(self):
    #    while True:
    #        t = self.rev.recv(1024)
    #        print(t)
    #        signal = self.controlQ.put(1)
            
